<template>
  <div
    v-if="props.show"
    class="winningPopup"
    :class="{ 'winningPopup-hidden': isStartAnimation }"
  >
    <img
      v-if="!isStartAnimation"
      class="box-bg"
      src="/image/lotterymoney/popup-numbers-gh-icon.svg"
    />
    <div
      ref="endCard"
      class="endCard"
      :class="{ 'box-animation': isStartAnimation }"
    ></div>
    <div
      class="box"
      ref="startCard"
      :class="{ 'box-animation': isStartAnimation }"
      @animationend="animationendFirst"
    >
      <div class="box-content">
        <div class="titlebg">{{ $t("lotteryMoney.hashdf") }}</div>
        <!-- 内容 -->
        <div class="content items-center">
          <div class="content-rank">
            {{ $t("lotteryMoney.depm") }}：
            <span style="color: #007bff">{{
              Number(rank) >= 999 ? ">100" : rank
            }}</span>
          </div>
          <div class="content-desc">
            {{
              Number(rank || 0) > 5
                ? $t("lotteryMoney.zjzl")
                : Number(rank || 0) == 1
                ? $t("lotteryMoney.gxndqlx")
                : $t("lotteryMoney.sljzyq")
            }}
          </div>
          <!-- 数字背景 -->
          <div class="content-numbers">
            <img
              class="content-numbers-bg"
              src="/image/lotterymoney/popup-numbers-bg0-icon.svg"
            />
            <RollingNumbers class="content-numbers-value" :grade="grade" />
          </div>
        </div>
        <!-- footer -->
        <div class="footer items-center">
          <div
            class="footer-btn"
            style="margin-right: 5px"
            @click.stop="startRank"
          >
            {{ $t("common.confirm") }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="winningPopup">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import RollingNumbers from "../rolling-numbers/index.vue";
import { useEventBus } from "@vueuse/core";
import { debounce, getOssFileUrl } from "@/utils";

const props = withDefaults(
  defineProps<{
    show: boolean;
    hash: any; // 哈希值
    rank: string | number; // 排名
    grade: string; // 得分
    x?: number; // 动画结束的 x 坐标
    y?: number; // 动画结束的 y 坐标
  }>(),
  {
    show: false,
    hash: "",
    rank: 101,
    grade: "00000000",
  }
);

const emit = defineEmits(["update:show", "confirm"]);

/**************************************** 抛物线撞击动画 ****************************************/
const startCard = ref();
const endCard = ref();
const isStartAnimation = ref(false); // 是否开始动画
const animationStartX = computed(() => {
  return `${rect.value.left / 2 || 0}px`;
});
const animationStartY = computed(() => {
  return `${rect.value.top || 0}px`;
});

const animationEndX = computed(() => {
  return `${props.x || 0}px`;
});
const animationEndY = computed(() => {
  return `${props.y - rect.value.height / 2 + 30}px`; // 用高度/2,是因为卡片高度缩小了 5 倍,这里折中处理,可以微调
});

const rect = ref({});

onMounted(() => {
  if (startCard.value) {
    rect.value = startCard.value.getBoundingClientRect();
    // console.log("rect.value-height", rect.value.height);
    // console.log(animationEndX.value, "--rect.left--", animationStartX.value);
    // console.log(animationEndY.value, "--rect.left--", animationStartY.value);
  }
});
onBeforeUnmount(() => {});

// 关闭弹窗
const popupClose = () => {
  emit("update:show", false);
};

// 点击-页面跳转
const openCardFirst = useEventBus("lottery-open-card-first");
const startRank = debounce(
  () => {
    isStartAnimation.value = true;
    // 第一名:展示裂痕
    if (props.rank == 1) {
      setTimeout(() => {
        openCardFirst.emit(1);
      }, 900);
    }
    // 动画结束
    setTimeout(() => {
      emit("confirm");
      popupClose();
    }, 1800);
  },
  500,
  false
);

const createShatterPieces = (container: any) => {
  // const containerRect = container.value.getBoundingClientRect();
  const fragment = document.createDocumentFragment();

  // 方式一:
  for (let i = 0; i < 9; i++) {
    const piece = document.createElement("img");
    piece.className = "piece";
    piece.src = getOssFileUrl({
      src: `/image/lotterymoney/card-sp${i}-icon.png`,
    }).src;
    // piece.style.backgroundColor = "#4CAF50";
    piece.style.top = `${Math.floor(i / 3) * 33.33}%`;
    piece.style.left = `${(i % 3) * 33.33}%`;
    piece.style.animation = "shatter 1s forwards";
    fragment.appendChild(piece);
  }
  container.value.appendChild(fragment);
  container.value.classList.add("broken");

  // 方式二 未完成
  // const rows = 3;
  // const cols = 3;
  // const pieceWidth = containerRect.width / cols;
  // const pieceHeight = containerRect.height / rows;

  // // const centerX = containerWidth / 2;
  // // const centerY = containerHeight / 2;

  // for (let row = 0; row < rows; row++) {
  //   for (let col = 0; col < cols; col++) {
  //     const piece = document.createElement("div");
  //     piece.className = "piece";
  //     piece.style.width = `${pieceWidth}px`;
  //     piece.style.height = `${pieceHeight}px`;
  //     piece.style.backgroundImage = `url('/image/lotterymoney/card-0-icon.png')`;
  //     piece.style.backgroundPosition = `-${col * pieceWidth}px -${
  //       row * pieceHeight
  //     }px`;
  //     piece.style.top = `${row * pieceHeight}px`;
  //     piece.style.left = `${col * pieceWidth}px`;

  //     container.value.appendChild(piece);
  //   }
  // }

  // // 强制重绘以应用初始样式
  // void container.value.offsetWidth;

  // // 延迟应用破碎效果
  // setTimeout(() => {
  //   const pieces = document.querySelectorAll(".piece");
  //   pieces.forEach((piece, index) => {
  //     const row = Math.floor(index / cols);
  //     const col = index % cols;

  //     const offsetX = (col - cols / 2) * pieceWidth;
  //     const offsetY = (row - rows / 2) * pieceHeight;
  //     const translateX = offsetX * 2;
  //     const translateY = offsetY * 2 + containerRect.offsetHeight / 2;

  //     piece.style.transform = `translate(${translateX}px, ${translateY}px) rotate(${
  //       Math.random() * 360
  //     }deg)`;
  //     piece.style.opacity = 0;
  //   });
  // }, 0);
};

// 第一阶段结束
const animationendFirst = () => {
  // 1. 隐藏原始卡片
  startCard.value.style.display = "none";
  // 2.
  createShatterPieces(endCard);
};
</script>
<style lang="scss" scoped>
.box-animation {
  @keyframes parabolicz {
    0% {
      scale: 1;
      left: 0;
      top: 0;
      // left: v-bind("animationStartX");
      top: v-bind("animationStartY");
    }
    100% {
      scale: 0.2;
      left: 0;
      // left: v-bind("animationEndX");
      // top: 0;
      top: v-bind("animationEndY");
    }
  }
  animation: parabolicz 1s forwards;
  // animation: parabolicz 1s cubic-bezier(0.42, 0, 0.58, 1) forwards;
}
.winning-overlay-class {
  background: rgba(0, 0, 0, 0);
}
.winningPopup {
  background-color: rgba(0, 0, 0, 0.6);
  position: fixed;
  touch-action: none;
  top: 0;
  left: 0;
  z-index: 999999;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  padding: 0 30 * 2px;
  &-hidden {
    background-color: transparent !important;
  }

  .box {
    position: absolute;
    width: 100%;
    &-content {
      border-radius: 12 * 2px;
      overflow: hidden;
      position: relative;
      margin: 0 30 * 2px;
      // padding: 0 30 * 2px;
      background: linear-gradient(180deg, #e2f0ff 0%, #fffeff 63.85%);
    }
    &-bg {
      position: absolute;
      width: 100vw;
      height: 100vw;
      scale: 1.2;
    }
  }
  .titlebg {
    height: 30 * 2px;
    line-height: 29 * 2px;
    margin: 20 * 2px 10 * 2px 16 * 2px 10 * 2px;
    color: #fff;
    text-align: center;
    font-size: 17 * 2px;
    font-weight: 590;

    text-align: center;
    font-weight: 590;
    background-image: url("/image/lotterymoney/popup-numbers-title-icon.svg");
    background-size: 100%;
    background-repeat: no-repeat;
  }

  .content {
    flex-direction: column;
    justify-content: center;
    padding: 0 15 * 2px;
    padding-bottom: 15 * 2px;
    &-rank {
      color: #141924;
      font-size: 15 * 2px;
      font-weight: 590;
      margin-bottom: 8 * 2px;
    }
    &-desc {
      font-size: 14 * 2px;
      color: #999da7;
      margin-bottom: 10 * 2px;
    }

    &-numbers {
      width: 100%;
      position: relative;
      min-height: 128 * 2px;

      &-bg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
      }
      &-value {
        justify-content: center;
        width: 100%;
        margin-top: 45 * 2px;
        // margin-bottom: 20 * 2px;
        padding: 0 30 * 2px;
      }
      &-hash {
        position: relative;
        z-index: 9;
        text-align: center;
        color: #fff2b2;
        font-size: 13 * 2px;
        font-weight: 590;
      }
    }
  }

  .footer {
    width: 100%;
    justify-content: space-around;
    border-top: 2px solid rgba(0, 0, 0, 0.1);
    padding: 12 * 2px 10 * 2px;

    &-btn {
      border-radius: 6 * 2px;
      background-color: #007bff;
      color: #fff;
      text-align: center;
      font-size: 15 * 2px;
      font-weight: 590;
      width: 100%;
      height: 36 * 2px;
      line-height: 36 * 2px;
      &-disabled {
        background-color: #a0ceff;
      }
      &-cancel {
        background-color: #fff;
        color: #007bff;
        border: 3px solid #007bff;
        margin-left: 10 * 2px;
      }
    }
  }
}
</style>
<!-- // 动画 -->
<style>
@keyframes bezier {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(500px, -300px);
  }
}

@keyframes shatter {
  0% {
    opacity: 1;
    transform: translate(0, 0) rotate(0deg);
  }
  100% {
    opacity: 0;
  }
}

.endCard {
  position: absolute;
  width: 100vw;
  height: 80vw;
  /* background-color: #4caf50; */
}
.broken .piece:nth-child(1) {
  transform: translate(-380px, -380px) rotate(-45deg);
}
.broken .piece:nth-child(2) {
  transform: translate(0, -380px) rotate(-30deg);
}
.broken .piece:nth-child(3) {
  transform: translate(380px, -380px) rotate(-15deg);
}
.broken .piece:nth-child(4) {
  transform: translate(-380px, 0) rotate(-30deg);
}
.broken .piece:nth-child(5) {
  transform: translate(0, 0) rotate(0deg);
}
.broken .piece:nth-child(6) {
  transform: translate(380px, 0) rotate(15deg);
}
.broken .piece:nth-child(7) {
  transform: translate(-380px, 380px) rotate(45deg);
}
.broken .piece:nth-child(8) {
  transform: translate(0, 380px) rotate(30deg);
}
.broken .piece:nth-child(9) {
  transform: translate(380px, 380px) rotate(15deg);
}

.piece {
  position: absolute;
  width: 33.33%;
  height: 33.33%;
  background-color: inherit;
  transition: transform 2s ease-in-out, opacity 2s ease-in-out;
}
</style>
